package com.gxa.autoparts.portal.service.impl;

import com.gxa.autoparts.core.common.ExceptionCode;
import com.gxa.autoparts.core.exception.BusinessException;
import com.gxa.autoparts.core.pojo.SystemMessage;
import com.gxa.autoparts.core.util.JsonUtil;
import com.gxa.autoparts.portal.service.SystemMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author ：looker
 * @date ：Created in 2022/1/12 14:14
 */
@Service
public class SystemMessageServiceImpl implements SystemMessageService {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    //系统消息的头部键  string
    private final static String MESSAGE = "MESSAGE:";
    //用户消息信息存储头部键   hash
    private final static String USERMESSAGE = "USERMESSAGE:";
    //系统总的消息的    list
    private final static String ALLMESSAGE = "ALLMESSAGE";
    //该用户删除消息的集合   list
    private final static  String DELMESSAGE = "DELMESSAGE:";

    @Override
    public void saveMessage(SystemMessage systemMessage) {
        Long userId = 1L;
        HashOperations<String, Object, Object> hashOperations = redisTemplate.opsForHash();
        ListOperations<String, Object> listOperations = redisTemplate.opsForList();
        ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();

        String s = JsonUtil.ObjectToString(systemMessage);
        stringObjectValueOperations.set(MESSAGE+systemMessage.getId(),s);

        listOperations.leftPush(ALLMESSAGE,systemMessage.getId());
    }

    @Override
    public Map<String, Object> getUserMessageById(Long userId) {
        HashMap<String, Object> data = new HashMap<>();

        ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
        ListOperations<String, Object> listOperations = redisTemplate.opsForList();
        HashOperations<String, Object, Object> hashOperations = redisTemplate.opsForHash();

        //全部消息
        List<Object> range = listOperations.range(ALLMESSAGE, 0, -1);
        if (!redisTemplate.hasKey(USERMESSAGE+userId)) {
           //该用户信息为空，直接从allmessae拿去所有消息
            for (Object o : range) {
                hashOperations.put(USERMESSAGE+userId,String.valueOf(o),"0");
            }
        }
        //用户的全部的消息Id  string集合
        Set<Object> keys = hashOperations.keys(USERMESSAGE + userId);
        //用户已删除消息的id   long集合
        List<Object> range1 = listOperations.range(DELMESSAGE + userId, 0, -1);
        //遍历全部消息，对用户不存在的新消息做更新
        for (Object o : range) {
            if(!keys.contains(String.valueOf(o)) && !range1.contains(o)){
                System.out.println("----------"+o.toString()+o.hashCode());
                hashOperations.put(USERMESSAGE+userId,String.valueOf(o),"0");
            }
        }
        //将更新后的消息  查出分为已读与未读
        List<Object> reader = new ArrayList<>();
        List<Object> notRead = new ArrayList<>();
        Map<Object, Object> entries = hashOperations.entries(USERMESSAGE + userId);
        Set<Map.Entry<Object, Object>> entries1 = entries.entrySet();
        for (Map.Entry<Object, Object> objectObjectEntry : entries1) {
            //消息Id
            Object key = objectObjectEntry.getKey();
            if (objectObjectEntry.getValue().equals("0")) {
                //未读
                Object o = stringObjectValueOperations.get(MESSAGE+key);
                SystemMessage systemMessage = JsonUtil.readToObject(o.toString(), SystemMessage.class);
                notRead.add(systemMessage);
            }else {
                //已读
                Object o = stringObjectValueOperations.get(MESSAGE+key);
                SystemMessage systemMessage = JsonUtil.readToObject(o.toString(), SystemMessage.class);
                reader.add(systemMessage);
            }
        }
        data.put("readed",reader);
        data.put("notRead",notRead);
        return data;
    }

    @Override
    public SystemMessage getById(Long id,Long userId) throws BusinessException {
        Boolean aBoolean = redisTemplate.hasKey(MESSAGE + id);
        if(!aBoolean){
            throw new BusinessException(ExceptionCode.NO_NEW);
        }
        ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
        HashOperations<String, Object, Object> hashOperations = redisTemplate.opsForHash();
        ListOperations<String, Object> listOperations = redisTemplate.opsForList();
        //拿出该用户已经删除的
        List<Object> range = listOperations.range(DELMESSAGE + userId, 0, -1);
        for (int i = 0; i < range.size(); i++) {
            if (range.get(i).toString().equals(""+id)) {
                throw new BusinessException(ExceptionCode.NO_ID);
            }
        }


        Object o = stringObjectValueOperations.get(MESSAGE + id);
        SystemMessage systemMessage = JsonUtil.readToObject(o.toString(), SystemMessage.class);
        //设为已读
        hashOperations.delete(USERMESSAGE+userId,String.valueOf(id));
        hashOperations.put(USERMESSAGE+userId,String.valueOf(id),"1");
        return systemMessage;
    }

    @Override
    public void delMessage(Long id, Long userId) throws BusinessException {
        if(id==null){
            throw new BusinessException(ExceptionCode.NO_ID);
        }
        ListOperations<String, Object> listOperations = redisTemplate.opsForList();
        HashOperations<String, Object, Object> hashOperations = redisTemplate.opsForHash();
        //进入删除集合
        listOperations.leftPush(DELMESSAGE+userId,id);
        //删除用户hash消息集合中的该消息
        hashOperations.delete(USERMESSAGE+userId,String.valueOf(id));
    }
}
